<?php
namespace common\help;
use yii;
use common\models\Notice;
use common\models\User;
use backend\components\Utools;
/*
 * 自定义全局公共方法
 */
class tools{
    /**
 * 发送通知函数
 * @param object 通知对象
 * @return string 字符串
 */

    public function behaviors()
    {

        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'add_time',// 自己根据数据库字段修改
                'updatedAtAttribute' => 'last_update', // 自己根据数据库字段修改
            ],
        ];
    }

    public static function send_notice($notice) {
        $model = new Notice();
        $notice['Notice'] = $notice;
        if($model->load($notice)){

            if(Yii::$app->id=='app-backend')//管理后端创建
            {
//                $from_id = Yii::$app->session['adminuser']->userid?Yii::$app->session['adminuser']->userid:1;//定时任务获取session
//                $model->from_id=$from_id;
                $model->isadmin=1;
            }
            else
            {
                $model->isadmin=0;
//                $model->from_id=Yii::$app->session['user']->id;//创建者id
            }

            if($model->validate())
            {
                $model->isNewRecord = true;
                $model->save() && $model->msg_id=0;

                return '1'; // 发送成功
            }
            else
            {
                return '-1'; //参数验证失败
            }
        }else{
            return '-2';  //传参错误
        }

    }

    public static function send_notices($notice) {

        $branch_array=explode(',',$notice[branch_id]);
        foreach($branch_array as $branch)
        {
            if($branch)
                $members[$branch]=User::find()->select('id')->where(" branch_id = {$branch} ")->orderBy(' id asc ')->all();
        }

        if(Yii::$app->id=='app-backend')//管理后端创建
        {
//            $from_id = Yii::$app->session['adminuser']->userid?Yii::$app->session['adminuser']->userid:1;//定时任务获取session
//            $notice['from_id']=$from_id;
            $notice['isadmin']=1;
        }
        else
        {
//            $notice['from_id']=Yii::$app->session['user']->id;//创建者id
            $notice['isadmin']=0;
        }

        foreach($members as $member)
        {
            if($member){
                foreach($member as $m){

                    $noticenew=new Notice();
                    $noticenew->title=$notice['title'];
                    $noticenew->content=$notice['content'];
                    $noticenew->from_id=$notice['from_id'];
                    $noticenew->isadmin=$notice['isadmin'];
                    $noticenew->to_id=$m->id;
                    $noticenew->type_id=$notice['type_id'];//暂定1
                    $noticenew->save();
                }
                return '1';
            }

        }

    }


}
?>